package com.tbl.modules.platform.controller.system;

import com.alibaba.fastjson.JSON;
import com.tbl.common.utils.PageData;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.les.constant.Const;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.constant.OperationCode;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.entity.system.Role;
import com.tbl.modules.platform.entity.system.User;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色controller
 * @author 70486
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController extends AbstractController {

    /**
     * 角色service
     */
    @Autowired
    private RoleService roleService;
    /**
     * 日志service
     */
    @Autowired
    private LogService logService;

    /**
     * 跳转到角色列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList.do")
    @ResponseBody
    public ModelAndView toList() {
        ModelAndView mv = new ModelAndView();
        User user = getSessionUser();
        OperationCode operationCode = roleService.selectOperationByRoleId(user.getRoleId(), MenuConstant.permission);
        mv.addObject("operationCode", operationCode);
        mv.setViewName("techbloom/platform/system/role/role_list");
        return mv;
    }

    /**
     * 获取角色列表
     * @param response
     * @param queryJsonString
     * @return Object
     */
    @RequestMapping(value = "/roleList.do")
    @ResponseBody
    public Object roleList(HttpServletResponse response, String queryJsonString) {
        Map<String, Object> map = new HashMap<>(5);
        if (!StringUtils.isEmpty(queryJsonString)){
            map = JSON.parseObject(queryJsonString);
        }

        PageTbl page = this.getPage();
        map.put("page", page.getPageno());
        map.put("limit", page.getPagesize());
        String sortName = page.getSortname();
        if (StringUtils.isEmptyString(sortName)) {
            sortName = "role_id";
            page.setSortname(sortName);
        }
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        PageUtils pageRole = roleService.getRolePageListS1(map);
        page.setTotalRows(pageRole.getTotalCount() == 0 ? 1 : pageRole.getTotalCount());
        map.put("rows", pageRole.getList());
        executePageMap(map, page);
        return map;
    }

    /**
     * 获取列表信息：下拉框使用
     * @param queryString
     * @param pageSize
     * @param pageNo
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getRoleList")
    @ResponseBody
    public Map<String, Object> getRoleList(String queryString, int pageSize, int pageNo, int generalType) {
        Map<String, Object> param = getAllParameter();
        PageTbl page = this.getPage();
        page.setPagesize(pageSize);
        page.setPageno(pageNo);
        PageUtils utils = roleService.getRolePageListS(page, param);
        Map<String, Object> map =new HashMap<>(2);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalCount());
        return map;
    }

    /**
     * 获取角色列表
     * @return List<Map<String,Object>>
     */
    @RequestMapping(value = "/getRoles")
    @ResponseBody
    public List<Map<String, Object>> getRoles() {
        return roleService.getRoles();
    }

    /**
     * 根据角色主键获取角色信息
     * @param rid
     * @return Role
     */
    @RequestMapping(value = "/getRoleById")
    @ResponseBody
    public Role getRoleById(Long rid) {
        Role role = null;
        if (rid != null){
            role = roleService.selectById(rid);
        }
        return role;
    }

    /**
     * 根据角色主键获取角色菜单
     * @param rid
     * @param type
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getMenulistByRoleId")
    @ResponseBody
    public List<Map<String, Object>> getMenulistByRoleId(Long rid, Integer type,Integer notInMenuNumber ,Integer menuNumber) {
        return roleService.getMenuListByRid(rid, type, notInMenuNumber, menuNumber);
    }

    /**
     * 返回到角色添加页面
     * @return String
     */
    @RequestMapping(value = "/role_edit")
    public String roledit() {
        return "techbloom/platform/system/role/role_edit";
    }

    /**
     * 保存/修改角色信息
     * @param  role
     * @return boolean
     */
    @RequestMapping(value = "/addRole")
    @ResponseBody
    public boolean addRole(Role role) {
        PageData pd = this.getPageData();
        boolean result = false;
        Long roleId = role.getRoleId();
        if(role.getRoleName() != null && !"".equals(role.getRoleName())) {
            if (roleId == null) {
                //新增(保存角色信息)
                roleId = roleService.saveForGernatedKey(role);
                if (roleId > 0) {
                    logService.logInsert("新增角色[" + role.getRoleName() + "]成功！", LogActionConstant.USER_ADD, this.getRequest());
                }
            } else {
                //更新(该方法新增/修改都可以)
                boolean res = roleService.saveRole(role);
                if (res) {
                    logService.logInsert("修改角色[" + role.getRoleName() + "]成功！", LogActionConstant.USER_EDIT, this.getRequest());
                }
            }
            //删除角色之前的权限，重新插入选中的角色权限
            roleService.delRoleMenuByRoleId(roleId, role.getType());
            String menuIds = pd.getString("menuId");
            if (!StringUtils.isEmptyString(menuIds)) {
                String[] menuArray = menuIds.split(",");
                //保存角色菜单信息
                result = roleService.saveRoleMenu(roleId, menuArray, role.getType());
            } else {
                //不选择菜单权限的时候
                result = true;
            }
        }

        return result;
    }


    /**
     * 删除
     * @return Object
     */
    @RequestMapping(value = "/delRole")
    @ResponseBody
    public Object deleteRole() {
        Map<String, Object> map = new HashMap<>(2);
        String ids = this.getPageData().getString("ids");
        String rolenames = roleService.getRoleNameByRoleids(ids);
        if (!StringUtils.isEmptyString(ids)) {
            List<Role> roleList = roleService.isHasRoleUser(ids);
            if (roleList != null && roleList.size() > 0) {
                String roleNames = "";
                for (Role role : roleList) {
                    roleNames += (StringUtils.isEmptyString(roleNames) ? "" : "，") + role.getRoleName();
                }
                map.put("roleInfo", roleNames);
                map.put("_result", false);
            } else {
                if (roleService.delRole(ids)){
                    logService.logInsert("删除了[" + rolenames + "]角色！", LogActionConstant.USER_DELETE, this.getRequest());
                    map.put("_result", true);
                }
            }
        }

        return map;
    }

    /**
     * 判断是否有相同名称的角色
     * @return Object
     */
    @RequestMapping(value = "/hasR")
    @ResponseBody
    public Object hasRole() {
        //true通过（不存在重复），false不通过（存在重复）
        HttpServletRequest request = this.getRequest();
        String roleName = request.getParameter("roleName");
        //true存在重复，false不存在重复
        boolean isHas = roleService.isHasRoleByName(roleName, request.getParameter("_id"));
        return !isHas;
    }

    /**
     * 权限
     * @return Map<String, String>
     */
    @SuppressWarnings("unchecked")
    public Map<String, String> getHC() {
        //shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }

}
